package com.tnl.hunter.webchat.controller;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.biz.hunter.dao.*;
import com.biz.hunter.db.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.biz.system.config.WebchatServiceConstant;
import com.biz.wechat.annotation.OAuthRequired;
import com.biz.wechat.util.SignUtil;
import com.tnl.hunter.dto.CompanyDto;


@Controller
public class CompanyController {

	private static final Logger logger = LoggerFactory.getLogger(CompanyController.class);

	@Autowired
	private TempCompanyDAO tempCompanyDAO;
	@Autowired
	private CompanyDAO companyDAO;
	@Autowired
	private EmployerDAO employerDAO;
	@Autowired
	private DomainDAO domainDAO;
	@Autowired
	private WXUserDAO userDAO;
	@Autowired
	private SysConfigRepo sysConfigService;
	@Autowired
	private CompanyLinkmanDAO companyLinkmanDAO;

	// HR认证创建公司第一页
	@OAuthRequired
	@RequestMapping(value = "wechat/company/toCreate_bak.page", method = RequestMethod.GET)
	public String toCreateCompany(HttpServletRequest request, int employerId, Model model) {
		
		HttpSession session = request.getSession();
		
		String openid = (String) session.getAttribute("OpenId");
		logger.debug("openid is " + openid);
		if (!StringUtils.hasText(openid)) {
			logger.info("empty openid ,wexin browser is needed.");
			return "wechat/headhunter/errorpage";
		}

		UserInfo user = userDAO.getByOpenId(openid);
		if (user == null) {
			logger.info("the openid " + openid + " is not subscribed");
			return "wechat/headhunter/errorpage";
		}
		
		Employer employer = employerDAO.getByOpenId(openid);
		if (employer == null) {
			model.addAttribute("errormsg", "系统错误, Hr用户不存在");
			return "wechat/headhunter/errorpage";
		}
		if(employer.getId() != employerId) {
			model.addAttribute("errormsg", "系统错误, Hr用户不存在");
			return "wechat/headhunter/errorpage";
		}
		
		model.addAttribute("employer", employer);
		List<Company> companies = companyDAO.getALL();
		model.addAttribute("companies", companies);
		
		/* */
		String ticket = sysConfigService.getJsTicket();
		logger.debug("js api ticket is "+ticket);
		String url = request.getRequestURL().toString();
		if (!StringUtils.isEmpty(request.getQueryString())) {  
	        url = url + "?" + request.getQueryString();  
	    } 
		logger.debug("request url is " + url);
			
		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);
			
		jsConfig config = new jsConfig();
		config.setAppid(WebchatServiceConstant.APPID);
		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));
			
		model.addAttribute("config", config);
		/* */
		
		return "wechat/headhunter/hr/hrxinxi21";
		
		//List<Domain> domains = domainDAO.getALL();
		//model.addAttribute("domains", domains);
		
		/*
		int compId = employer.getCompanyId();
		String compName = employer.getCompanyName();
		if (compId == 0) {
			//未绑定可以进行选择绑定或者创建
			logger.debug("did not binded any company");
			//return toEditCompany(request,employerId,compId,model);
			model.addAttribute("employer", employer);

			return "wechat/headhunter/hr/hrxinxi21";
		}
		
		if (StringUtils.hasText(compName)) {
			logger.debug("it is a temp binded company");
			// Company comp = tempCompanyDAO.getById(compId);
			
			Company comp = tempCompanyDAO.getByEmployerId(employer.getId());
			if (comp != null) {
				model.addAttribute("company", comp);
			}
			return "wechat/headhunter/hr/hrxinxi";
		}
		
		logger.debug("it is a  binded company");
		Company comp = companyDAO.getById(compId);
		if (comp != null) {
			model.addAttribute("tempcompany", comp);
		}
		logger.debug("the employer binded one Company which is authorized");
		//return toUploadFile(request, employerId, compId, model);
		return "wechat/headhunter/hr/hrxinxi";
		*/

	}

	// 新版
	@OAuthRequired
	@RequestMapping(value = "wechat/company/create2_2.do", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> createCompanyStep2_2( HttpServletRequest request, ModelMap model, CompanyDto dto) {
		
		Map<String, Object> returnMap = new HashMap<String, Object>();
		
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");
		if (!StringUtils.hasText(openId)) {
			logger.info("您需要在微信平台使用");
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "您需要在微信平台使用");
			return returnMap;
		}
		
		boolean isTemp = false;
		
		int hrId = dto.getHrid();
		if (hrId == 0) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "必须提供HR信息");
			return returnMap;
		}
		Employer employer = employerDAO.getById(hrId);
		if (employer == null) {
			returnMap.put("errorcode", "2");
			returnMap.put("msg", "该HR信息不存在");
			return returnMap;
		}
		
		// 分情况进行处理
		String companyname = dto.getCompanyname();
		String bizcode = dto.getBizcode();
		
		Company cp = companyDAO.getByName(companyname);
		
		if(cp == null) {
			isTemp = true;
			cp = tempCompanyDAO.getByName(companyname);
		}
		if(cp == null) {
			// Hr的公司不在company里，也不在tempcompany里，那么需要创建HR公司
			session.setAttribute("CompanyDTO", dto);
			returnMap.put("errorcode","1");
			returnMap.put("msg", "请继续创建公司信息");
			return returnMap;
		} else {
			// 如果数据库里已经有该公司的了，那么还需要分情况检查
			/* 
			// 这段逻辑不要删除，因为现在公司都没有营业执照号码
			if(bizcode.compareToIgnoreCase(cp.getLicenseCode()) == 0) {
				// 分情况判断是company还是tempcompany
				if(!isTemp) {
					// 提示公司未认证
					employer.setBinded(-1);
					employer.setCompanyId(cp.getId());
					employer.setCompanyName(cp.getName());
					employerDAO.update(employer);
					returnMap.put("errorcode","5");
					returnMap.put("msg", "该公司尚未通过认证，请耐心等待");
					return returnMap;
					
				} else {
					// 如果是tempcompany公司
					Long count = employerDAO.getBindedNumByCompanyId(cp.getId(),companyname);
					// 检查绑定是否超过限制
					if(count > 4) {
						employer.setBinded(-1);
						employer.setCompanyId(cp.getId());
						employer.setCompanyName(cp.getName());
						employerDAO.update(employer);
						returnMap.put("errorcode","3");
						returnMap.put("msg", "该公司绑定人数已超限制");
						return returnMap;
					}
					// 绑定它
					employer.setBinded(0);
					employer.setCompanyId(cp.getId());
					employer.setCompanyName(cp.getName());
					int result = employerDAO.update(employer);
					if(result == -1) {
						returnMap.put("errorcode","-3");
						returnMap.put("msg", "操作失败");
						return returnMap;
					}
					returnMap.put("errorcode","0");
					returnMap.put("msg", "公司成功绑定");
					return returnMap;
				}
			} else {
				// 提示错误
				returnMap.put("errorcode","3");
				returnMap.put("msg", "你输入的公司名已经存在系统中，但和公司的营业执照代码不匹配");
				return returnMap;
			}
			*/
			// 暂时性算法
			if(isTemp) {
				// 提示公司未认证
				employer.setBinded(-1);
				employer.setCompanyId(cp.getId());
				employer.setCompanyName(cp.getName());
				employerDAO.update(employer);
				returnMap.put("errorcode","5");
				returnMap.put("msg", "该公司尚未通过认证，请耐心等待");
				return returnMap;
			} else {
				String cpbizcode = cp.getLicenseCode();
				if(StringUtils.hasText(cpbizcode)) {
					// 1. 如果存在营业执照代码
					if(bizcode.compareToIgnoreCase(cpbizcode) == 0) {
						Long count = employerDAO.getBindedNumByCompanyId(cp.getId(), companyname);
						// 检查绑定是否超过限制
						if(count > 4) {
							employer.setBinded(-1);
							employer.setCompanyId(cp.getId());
							employer.setCompanyName(cp.getName());
							employerDAO.update(employer);
							returnMap.put("errorcode","3");
							returnMap.put("msg", "该公司绑定人数已超限制");
							return returnMap;
						}
						// 绑定它
						employer.setBinded(0);
						employer.setCompanyId(cp.getId());
						employer.setCompanyName(cp.getName());
						int result = employerDAO.update(employer);
						if(result == -1) {
							returnMap.put("errorcode","-3");
							returnMap.put("msg", "操作失败");
							return returnMap;
						}
						returnMap.put("errorcode","0");
						returnMap.put("msg", "公司成功绑定");
						return returnMap;
					} else {
						// 提示错误
						returnMap.put("errorcode","3");
						returnMap.put("msg", "你输入的公司名已经存在系统中，但和公司的营业执照代码不匹配");
						return returnMap;
					}
				} else {
					// 2. 如果不存在营业执照代码
					// 绑定它
					employer.setBinded(0);
					employer.setCompanyId(cp.getId());
					employer.setCompanyName(cp.getName());
					int result = employerDAO.update(employer);
					if(result == -1) {
						returnMap.put("errorcode","-3");
						returnMap.put("msg", "操作失败");
						return returnMap;
					}
					returnMap.put("errorcode","0");
					returnMap.put("msg", "公司成功绑定");
					return returnMap;
				}
				
			}
		}
	}

	// 新版：HR认证创建公司第二页
	@OAuthRequired
	@RequestMapping(value = "wechat/company/toCreate.page", method = RequestMethod.GET)
	public String toEditCompanyInfo(HttpServletRequest request, int employerId,  Model model) {
		
		HttpSession session = request.getSession();
		
		String openid = (String) session.getAttribute("OpenId");
		logger.debug("openid is " + openid);
		if (!StringUtils.hasText(openid)) {
			logger.info("empty openid ,wexin browser is needed.");
			return "wechat/headhunter/errorpage";
		}
		
		Employer employer = employerDAO.getByOpenId(openid);
		if (employer == null) {
			logger.error("the input parameter is not correct");
			model.addAttribute("title","温馨提示" );
			model.addAttribute("msg", "对话超时，需要重新进入");
			return "wechat/headhunter/msgpage";
		}
		model.addAttribute("employer", employer);

		Company company = tempCompanyDAO.getByEmployerIdAndName(employerId,employer.getCompanyName());
		if (company == null) {
			Company com =  new Company();
			com.setName(employer.getCompanyName());
			model.addAttribute("tempcompany", com);
		} else {
			CompanyLinkman linkman = companyLinkmanDAO.getByCompanyidAndName(company.getId(),company.getName());
			model.addAttribute("linkman", linkman);
			model.addAttribute("tempcompany", company);
		}

		List<Domain> domains = domainDAO.getAllSubDomain();
		model.addAttribute("domains", domains);
		
		/* */
		String ticket = sysConfigService.getJsTicket();
		logger.debug("js api ticket is "+ticket);
		String url = request.getRequestURL().toString();
		if (!StringUtils.isEmpty(request.getQueryString())) {  
	        url = url + "?" + request.getQueryString();  
	    } 
		logger.debug("request url is " + url);
			
		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);
			
		jsConfig config = new jsConfig();
		config.setAppid(WebchatServiceConstant.APPID);
		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));
			
		model.addAttribute("config", config);
		/* */
		
		return "wechat/headhunter/hr/hrxinxi22";
	}
	
	// 新版
	@OAuthRequired
	@RequestMapping(value = "wechat/company/create1_2.do", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> createCompanyStep1_2(HttpServletRequest request, ModelMap model, CompanyDto dto) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		
		HttpSession session = request.getSession();
		String openid = (String) session.getAttribute("OpenId");
		if (!StringUtils.hasText(openid)) {
			logger.info("您需要在微信平台使用");
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "您需要在微信平台使用");
			return returnMap;
		}

		int hrId = dto.getHrid();
		if (hrId == 0) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "必须先HR猎头信息");
			return returnMap;
		}

		Employer employer = employerDAO.getByOpenId(openid);
		if (employer == null) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "该HR信息不存在");
			return returnMap;
		}
		if(employer.getId() != hrId) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "提交的HR信息不一致");
			return returnMap;
		}
		
		session.removeAttribute("CompanyDTO");
		
//		String companyname = dto.getCompanyname();
//		Company company = companyDAO.getByName(companyname);
//
//		if(company!=null) {
//			returnMap.put("errorcode", "1");
//			returnMap.put("msg", "该公司正在审核中，请耐心等待");
//			return returnMap;
//		}

//		Company company = tempCompanyDAO.getByName(companyname);
//		if(company!=null) {
//			returnMap.put("errorcode", "2");
//			returnMap.put("msg", "该公司正在审核中，请耐心等待");
//			return returnMap;
//		}
		
		// 那就创建新公司
		Company byEmployerId = tempCompanyDAO.getByEmployerIdAndName(hrId,employer.getCompanyName());
		Company htcompany = new Company();
		htcompany.setName(dto.getCompanyname());
		htcompany.setEnglishName(dto.getEnglishName());
		htcompany.setContact(dto.getCompanycontact());
		htcompany.setAddress(dto.getCompanyaddress());
		htcompany.setEmail(dto.getCompanyemail());
		htcompany.setPhone(dto.getCompanyphone());
		htcompany.setLicenseCode(dto.getBizcode());
		htcompany.setOrgnizationCode(dto.getOrgcode());
		htcompany.setDomain(dto.getDomainid());
		htcompany.setApproved(0);
		htcompany.setEmployerid(hrId);
		htcompany.setCreateId(hrId);
		//新加
		htcompany.setTags(dto.getTags());
		htcompany.setScope(dto.getScope());
		htcompany.setPosition(dto.getPosition());
		htcompany.setProperty(dto.getProperty());

		Date now = new Date();
		htcompany.setCreateDate(now.getTime());
		if (byEmployerId == null) {
			int result = tempCompanyDAO.save(htcompany);
			if (result == -1) {
				returnMap.put("errorcode", "40001");
				returnMap.put("msg", "创建公司失败，请和管理员联系");
				return returnMap;
			}
			int companyid = result;
			htcompany.setId(companyid);

			//add 联系人表
			companyLinkmanDAO.save(htcompany);
		} else {
			htcompany.setId(byEmployerId.getId());
			tempCompanyDAO.updateTemp(htcompany);
			companyLinkmanDAO.updateLinkman(htcompany);
		}


		// 更新hunter信息， 绑定它
		employer.setBinded(-1);
		employer.setCompanyId(htcompany.getId());
		employer.setCompanyName(htcompany.getName());
		int result = employerDAO.update(employer);
		if(result == -1) {
			returnMap.put("errorcode","40001");
			returnMap.put("msg", "操作失败");
			return returnMap;
		}
		returnMap.put("errorcode","0");
		returnMap.put("msg", "公司成功创建并绑定");
		return returnMap;
	}

    @OAuthRequired
	@RequestMapping(value = "wechat/company/toUploadFile.page", method = RequestMethod.GET)
	public String toUploadFile(HttpServletRequest request, Model model) {
    	
    	HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");
		if (!StringUtils.hasText(openId)) {
			logger.info("session过期,请关闭重试");
			return "wechat/headhunter/errorPage";
		}
		
		Employer employer = employerDAO.getByOpenId(openId);
		if (employer == null) {
			logger.error("the employer is null");
			return "wechat/headhunter/errorPage";
		}
		model.addAttribute("employer", employer);
		// Company company = null;
		// if (StringUtils.hasText(employer.getCompanyName())) {
		// company = tempCompanyDAO.getById(companyId);
		// model.addAttribute("tempcompany", company);
		// } else {
		// company = companyDAO.getById(companyId);
		// model.addAttribute("company", company);
		// }

		String ticket = sysConfigService.getJsTicket();
		logger.debug("js api ticket is "+ticket);
		String url = request.getRequestURL().toString();
		if (!StringUtils.isEmpty(request.getQueryString())) {  
            url = url + "?" + request.getQueryString();  
        } 
		logger.debug("request url is " + url);
		
		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

		jsConfig config = new jsConfig();
		config.setAppid(WebchatServiceConstant.APPID);
		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));
		
		model.addAttribute("config", config);
		return "wechat/headhunter/hr/hrxinxi3";
	}

	@OAuthRequired
	@RequestMapping(value = "wechat/companty/uploadFile.do", method = RequestMethod.GET)
	public  String  uploadFile(HttpServletRequest request, int hrId, int companyId,  MultipartFile file, Model model) {
		
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");
		if (!StringUtils.hasText(openId)) {
			logger.info("session过期,请关闭重试");
			return "wechat/headhunter/errorPage";
		}
		
		// Employer employer = employerDAO.getById(hrId);
		Employer employer = employerDAO.getByOpenId(openId);
		if (employer == null) {
			//msg.setErrorcode("4001");
			logger.error("invalid input parameter about hrId");
			return "wechat/headhunter/errorpage";
		}
		if(employer.getId() != hrId) {
			logger.error("invalid input parameter about hrId");
			return "wechat/headhunter/errorpage";
		}
		// 2 employer
		int compId = employer.getCompanyId();
		String compName = employer.getCompanyName();
		
		if(compId <=0) {
			logger.error("invalid input parameter about hrId");
			return "wechat/headhunter/errorpage";
		}
		// 3 company
		Company company = null;
		company = tempCompanyDAO.getById(compId);
		if (company == null) {
			logger.error("invalid input parameter about companyname");
			return "wechat/headhunter/errorpage";
		}
		
		String realPath = FileController.BASE_PATH;
		logger.debug("path is " + realPath);
		//创建文件 
	    File dir=new File(realPath);
	    if(!dir.exists()){
	        dir.mkdirs();
	    }
	    String id=currentDate();
	    String fileName=file.getOriginalFilename();
	    String img=id+fileName.substring(fileName.lastIndexOf("."));//zhao.jpg
	    FileOutputStream imgOut;
		try {
			imgOut = new FileOutputStream(new File(dir,img));//根据 dir 抽象路径名和 img 路径名字符串创建一个新 File 实例。
		    imgOut.write(file.getBytes());//返回一个字节数组文件的内容
		    imgOut.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
		company.setImage(img);
		tempCompanyDAO.update(company);
		
		/*
		// 正式公司，客户是没有资格上传执照的。否则要乱套了
		if (StringUtils.hasText(compName)) {
			company = tempCompanyDAO.getById(compId);
			if (company == null) {
				logger.error("invalid input parameter about companyname");
				return "wechat/headhunter/errorpage";
			}
			company.setImage(resId);
			tempCompanyDAO.update(company);
		} else {
			company = companyDAO.getById(compId);
			if (company == null) {
				logger.error("invalid input parameter about companyId");
				return "wechat/headhunter/errorpage";
			}
			company.setImage(resId);
			companyDAO.update(company);
		}
		*/

		//String realPath = request.getSession().getServletContext().getRealPath("/resources/images/company");
		//String realPath = FileController.BASE_PATH;
		//String token = sysConfigService.getAccessToken();
		//MediaAPI.getMediaFromWechat(realPath, resId, token);
		
		/* */
		String ticket = sysConfigService.getJsTicket();
		logger.debug("js api ticket is "+ticket);
		String url = request.getRequestURL().toString();
		if (!StringUtils.isEmpty(request.getQueryString())) {  
	        url = url + "?" + request.getQueryString();  
	    } 
		logger.debug("request url is " + url);
			
		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);
			
		jsConfig config = new jsConfig();
		config.setAppid(WebchatServiceConstant.APPID);
		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));
			
		model.addAttribute("config", config);
		/* */

		return "wechat/headhunter/hr/hrxinxi4";
	}
	public static String currentDate() {
		return new SimpleDateFormat("yyyyMMddHHmmss").format(System
				.currentTimeMillis());
	}
 
	/*
	@RequestMapping(value = "wechat/company/create.do", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> createCompanyStep1(
			HttpServletRequest request, CompanyDto dto) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		int result = -1;
		boolean isTemp = false;
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");

		int hrId = dto.getHrid();
		if (hrId == 0) {
			logger.error("the input hr id is 0");
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "invalid paramter in request for the hrId");
			return returnMap;
		}
		Employer employer = employerDAO.getById(hrId);
		if (employer == null) {
			logger.error("can not get the employer by the provided id" + hrId);
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "invalid paramter in request for the hr id = "
					+ hrId);
			return returnMap;
		}
		//1.check name exist
		String companyname = dto.getCompanyname();
		String orgcode = dto.getOrgcode();
		Company cp = companyDAO.getByName(companyname);

		if (cp == null) {
			isTemp = true;
			cp = tempCompanyDAO.getByName(companyname);
			//return bindTempCompany();
		}
		
		if(cp == null) {
			// 猎头的公司不在数据库里，那么需要创建猎头公司
			session.setAttribute("companyDTO", dto);
			returnMap.put("errorcode","1");
			returnMap.put("msg", "请继续创建公司信息");
			return returnMap;
		} else {
			// 如果数据库里已经有该公司的了，那么检查orgcode是否正确
			if(orgcode.equalsIgnoreCase(cp.getOrgnizationCode())) {
				// 检查绑定是否超过限制
				Long count = employerDAO.getBindedNumByCompanyId(cp.getId(),companyname);
				//int countI = getBinded(cp.getId(),isTemp);
				if(count > 4) {
					employer.setBinded(-1);
					employer.setCompanyId(cp.getId());
					if(isTemp){
						employer.setCompanyName(cp.getName());
					}
					employerDAO.update(employer);
					returnMap.put("errorcode","3");
					returnMap.put("msg", "该公司绑定人数已超限制");
					return returnMap;
				}
				// 绑定它
				employer.setBinded(1);
				employer.setCompanyId(cp.getId());
				if(isTemp){
					employer.setCompanyName(cp.getName());
				}
				result = employerDAO.update(employer);
				if(result == -1) {
					returnMap.put("errorcode","-3");
					returnMap.put("msg", "操作失败");
					return returnMap;
				}
				returnMap.put("errorcode","0");
				returnMap.put("msg", "公司成功绑定");
				return returnMap;
			} else {
				// 提示错误
				returnMap.put("errorcode","3");
				returnMap.put("msg", "你输入的公司名已经存在系统中，但和公司的组织结构代码不匹配");
				return returnMap;
			}
		}
		
	}

	@OAuthRequired
	@RequestMapping(value = "wechat/company/toCreate2.page", method = RequestMethod.GET)
	public String toCreateCompanyStep2(HttpServletRequest request,  Model model) {
		HttpSession session = request.getSession();
		String openid = (String) session.getAttribute("OpenId");
	
		logger.debug("openid is " + openid);
		if (!StringUtils.hasText(openid)) {
			logger.info("Session is expired.");
			return "wechat/headhunter/errorpage";
		}
		Employer employer = employerDAO.getByOpenId(openid);
		
		model.addAttribute("employer", employer);
		// List<Company> companies = companyDAO.getALL();
		// model.addAttribute("companies", companies);
		List<Domain> domains = domainDAO.getALL();
		model.addAttribute("domains", domains);
		CompanyDto cp = (CompanyDto)session.getAttribute("companyDTO");
		 Company company = new  Company();
		company.setOrgnizationCode(cp.getOrgcode());
		company.setName(cp.getCompanyname());
		
		logger.error("the employer binded one Company which is authorized");
		//return toUploadFile(request, hrId, compId, model);
		model.addAttribute("tempcompany", company);
		return "wechat/headhunter/hr/hrxinxi22";
		
	}
	
	//@OAuthRequired
	@RequestMapping(value = "wechat/company/create2.do", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> createCompanyStep2(
			HttpServletRequest request, CompanyDto dto) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		int result = -1;
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");

		int hrId = dto.getHrid();
		if (hrId == 0) {
			logger.error("the input hr id is 0");
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "invalid paramter in request for the hrId");
			return returnMap;
		}
		Employer employer = employerDAO.getById(hrId);
		if (employer == null) {
			logger.error("can not get the employer by the provided id" + hrId);
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "invalid paramter in request for the hr id = "
					+ hrId);
			return returnMap;
		}

		int companyId = persistentCompany(dto);
		if (companyId == -1) {
			logger.error("failed to persistent Company");
			returnMap.put("errorcode", "50105");
			returnMap.put(
					"msg",
					" failed to persistent the  company ("
							+ dto.getCompanyname() + ")  Id ="
							+ dto.getCompanyid());
			returnMap.put("data", companyId);
			return returnMap;
		}
		Company comp = tempCompanyDAO.getById(companyId);
		result = bindTempCompany(hrId, comp);

		if (result == -1) {
			logger.error("failed to binde the company and employer");
			returnMap.put("errorcode", "50106");
			returnMap.put("msg", " failed to bind the hunter (" + hrId
					+ ") to company Id =" + companyId);
			returnMap.put("data", companyId);
			return returnMap;
		}

		returnMap.put("errorcode", "200");
		returnMap.put("msg", "create company successfully");
		returnMap.put("data", companyId);
		return returnMap;
	}

	private int persistentCompany(CompanyDto dto) {
		int companyId = dto.getCompanyid();

		Company comp = tempCompanyDAO.getById(companyId);
		if (comp != null) {// update
			// 认证通过，不再update
			if (comp.getApproved() == 1) {
				return companyId;
			}
			comp.setName(dto.getCompanyname());
			comp.setContact(dto.getCompanycontact());
			comp.setAddress(dto.getCompanyaddress());
			comp.setEmail(dto.getCompanyemail());
			comp.setPhone(dto.getCompanyphone());
			comp.setLicenseCode(dto.getBizcode());
			comp.setOrgnizationCode(dto.getOrgcode());
			comp.setCreateId(dto.getHrid());
			int result = tempCompanyDAO.update(comp);
			if (result == -1) {
				logger.error("failed to update hunter comapny" + companyId);
				return -1;
			}
			return companyId;
		}
		int hrId = dto.getHrid();
		comp = tempCompanyDAO.getByEmployerId(hrId);
		if (comp != null) {
			logger.error("ther user has already created one company.");
			return -1;
		}
		// create new company
		comp = new Company();
		comp.setName(dto.getCompanyname());
		comp.setContact(dto.getCompanycontact());
		comp.setAddress(dto.getCompanyaddress());
		// comp.setEmail(dto.);
		comp.setPhone(dto.getCompanyphone());
		comp.setLicenseCode(dto.getBizcode());
		comp.setOrgnizationCode(dto.getOrgcode());
		comp.setApproved(0);
		Date now = new Date();
		comp.setCreateDate(now.getTime());
		comp.setCreateId(dto.getHrid());
		int result = tempCompanyDAO.save(comp);
		if (result == -1) {
			logger.error("failed to update hunter comapny" + comp.getName());
			return -1;
		}
		// companyId = comp.getId();
		comp.setId(result);
		return result;
	}

	private int bindCompany(int hunterId, Company company) {

		int companyId = company.getId();
		Employer employer = employerDAO.getById(hunterId);
		logger.debug("update the hunter info with the companyid "
				+ company.getId());
		List<Employer> list = employerDAO.getBindedByCompanyId(companyId);
		if (list == null || list.size() <= 4) {
			employer.setBinded(0);
		} else {
			logger.info("there are 5 person binded the company with id ="
					+ companyId);
			employer.setBinded(-1);
		}
		employer.setCompanyId(companyId);
		employer.setCompanyName("");
		int result = employerDAO.update(employer);
		return result;
	}

	private int bindTempCompany(int hunterId, Company company) {
		int companyId = company.getId();
		Employer employer = employerDAO.getById(hunterId);
		logger.debug("update the hunter info with the companyid "
				+ company.getId());
		List<Employer> list = employerDAO.getBindedByCompanyId(companyId);
		if (list == null || list.size() <= 4) {
			employer.setBinded(0);
		} else {
			logger.info("there are 5 person binded the company with id ="
					+ companyId);
			employer.setBinded(-1);
		}
		employer.setCompanyId(companyId);
		employer.setCompanyName(company.getName());
		int result = employerDAO.update(employer);
		return result;
	}

	@RequestMapping(value = "wechat/company/bindCompany.do", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> bindCompany(
			HttpServletRequest request, CompanyDto dto) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		int result = -1;
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("openId");

		int hrId = dto.getHrid();
		if (hrId == 0) {
			logger.error("the input hr id is 0");
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "invalid paramter in request for the hrId");
			return returnMap;
		}
		Employer employer = employerDAO.getById(hrId);
		if (employer == null) {
			logger.error("can not get the employer by the provided id" + hrId);
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "invalid paramter in request for the hr id = "
					+ hrId);
			return returnMap;
		}
		int companyId = dto.getCompanyid();
		//is already binded?
		int binded = employer.getBinded();
		if(binded == 1){
			returnMap.put("errorcode", "200");
			returnMap.put("msg", "create company successfully");
			returnMap.put("data", companyId);
			return returnMap;
		}

		Company comp = companyDAO.getById(companyId);
		String orgCode = dto.getOrgcode();
		String bizCode = dto.getBizcode();
		boolean companyExist = validateCompany(comp, orgCode, bizCode);
		if (!companyExist) {
			logger.error("there is not any company with the orgcode is "
					+ orgCode);
			returnMap.put("errorcode", "40001");
			returnMap.put("msg",
					"验证失败,请仔细填写机构代码和营业执照编码");
			return returnMap;
		}

		result = bindCompany(hrId, comp);

		if (result == -1) {
			logger.error("failed to binde the company and employer");
			returnMap.put("errorcode", "50106");
			returnMap.put("msg", " failed to bind the hunter (" + hrId
					+ ") to company Id =" + companyId);
			returnMap.put("data", companyId);
			return returnMap;
		}

		returnMap.put("errorcode", "200");
		returnMap.put("msg", "create company successfully");
		returnMap.put("data", companyId);
		return returnMap;
	}

	private boolean validateCompany(Company comp, String orgCode, String bizCode) {
		if (comp == null) {
			return false;
		}
		if (!StringUtils.hasText(orgCode)) {
			return false;
		}
		if (!StringUtils.hasText(bizCode)) {
			return false;
		}
		if (comp.getOrgnizationCode().equals(orgCode)
				&& bizCode.equals(comp.getLicenseCode())) {
			return true;
		}
		return false;
	}
	

	@OAuthRequired
	@RequestMapping(value = "wechat/company/toEdit.page", method = RequestMethod.GET)
	public String toEditCompany(HttpServletRequest request, int hrId,
			int companyId, Model model) {
		// 只有是创建者，或者没有认证的才能修改。
		Employer employer = employerDAO.getById(hrId);
		model.addAttribute("employer", employer);
		Company company = tempCompanyDAO.getById(companyId);
		model.addAttribute("tempcompany", company);
		List<Company> companies = tempCompanyDAO.getALL();
		model.addAttribute("companies", companies);

		return "wechat/headhunter/hr/hrxinxi21";
	}

	// 认证一个公司，就是把temp公司转为公司的过程。
	@RequestMapping(value = "wechat/company/Authorize.page", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> authorizeCompany(
			HttpServletRequest request, int hunterId, int tempId, int companyId) {
		Map<String, Object> map = new HashMap<String, Object>();
		Employer hunter = employerDAO.getById(hunterId);
		if (hunter == null) {
			map.put("errorcode", "500");
			map.put("msg", "can not find the hunter with the provided id ="
					+ hunterId);
			return map;
		}
		if (hunter.getCompanyId() != 0) {
			map.put("errorcode", "500");
			return map;
		}
		if (!StringUtils.hasText(hunter.getCompanyName())) {
			map.put("errorcode", "500");
			return map;
		}

		Company tempCompany = tempCompanyDAO.getById(tempId);
		if (hunter.getCompanyId() != 0) {
			map.put("errorcode", "500");
			return map;
		}
		Company company = companyDAO.getById(companyId);
		if (hunter.getCompanyId() != 0) {
			map.put("errorcode", "500");
			return map;
		}
		//tempCompany.setApproved(approved);
		int id = companyDAO.save(tempCompany);
		if (id != -1) {
			tempCompanyDAO.deleteById(tempId);
		}

		hunter.setCompanyName(null);
		//hunter.setBinded(1);
		hunter.setCompanyId(companyId);

		return map;
	}
	*/
}
